//
//  ArtDrawView.m
//  ArtJust
//
//  Created by slience on 2022/11/13.
//

#import "ArtDrawView.h"
#import "ArtStroke.h"

@interface ArtDrawView() {
    CGMutablePathRef currentPath;//路径
}

//存储所有的路径
@property (nonatomic, strong) NSMutableArray *stroks;

@end

@implementation ArtDrawView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _stroks = [[NSMutableArray alloc] initWithCapacity:1];
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    currentPath = CGPathCreateMutable();
    ArtStroke *stroke = [[ArtStroke alloc] init];
    stroke.path = currentPath;
    stroke.blendMode = _isEarse ? kCGBlendModeDestinationIn : kCGBlendModeNormal;
    stroke.strokeWidth = _isEarse ? 20.0 : _lineWidth;
    stroke.lineColor = _isEarse ? [UIColor clearColor] : _lineColor;
    [_stroks addObject:stroke];
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGPathMoveToPoint(currentPath, NULL, point.x, point.y);
}


-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGPathAddLineToPoint(currentPath, NULL, point.x, point.y);
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (ArtStroke *stroke in _stroks) {
        [stroke strokeWithContext:context];
    }
    
}
- (void)dealloc {
    CGPathRelease(currentPath);
}

/** 清屏 */
- (void)clearScreen {
    _isEarse = NO;
    [_stroks removeAllObjects];
    [self setNeedsDisplay];
}

/** 撤消操作 */
- (void)revokeScreen {
    _isEarse = NO;
    [_stroks removeLastObject];
    [self setNeedsDisplay];
}

/** 擦除 */
- (void)eraseSreen {
    self.isEarse = YES;
}
/** 设置画笔颜色 */
- (void)setStrokeColor:(UIColor *)lineColor {
    _isEarse = NO;
    self.lineColor = lineColor;
//    [self setNeedsDisplay];
}
/** 设置画笔大小 */
- (void)setStrokeWidth:(CGFloat)lineWidth {
    _isEarse = NO;
    self.lineWidth = lineWidth;
}

-(void)setLineColor:(UIColor *)lineColor {
    _isEarse = NO;
    _lineColor = lineColor;
}
-(void)setLineWidth:(CGFloat)lineWidth {
    _isEarse = NO;
    _lineWidth = lineWidth;
    
}
@end
